//
//  UploadImageViewController.swift
//  jiaoyi
//
//  Created by wjk on 2018/11/3.
//  Copyright © 2018 wjk. All rights reserved.
//

import UIKit
import CLImagePickerTool
import Kingfisher
import GTMBase64
import JWTDecode
import SwiftyJSON

class UploadImageViewController: BaseViewController,UITableViewDelegate,UITableViewDataSource {

    @IBOutlet weak var btnImg: UIButton!
    
    var bl:changeUserBlock?
    var jd:JSON = JSON()
    @IBOutlet weak var tableView: UITableView!
    var data:[String:Any] = ["key":"","value":""]
    
    var urls:[String] = [String]()
    
    var uiimageData:[UIImage] = [UIImage]()
    
    var imgData:[String] = [String]()
    
    var isSave:Bool = false
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.imgData.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "addImageTableViewCell") as! AddImageTableViewCell
        cell.selectionStyle = .none
        let url = self.imgData[indexPath.row]
        
        if url.isEmpty {
            cell.btn.setImage(R.image.add(), for: .normal)
        }else {
            if url.hasPrefix("http://") || url.hasPrefix("https://") {
                cell.btn.kf.setBackgroundImage(with: ImageResource.init(downloadURL: URL.init(string:url)!), for: .normal)
                cell.btn.setImage(UIImage(), for: .normal)
            }else {
                cell.btn.setImage(self.uiimageData[indexPath.row], for: .normal)
            }
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let imgp = CLImagePickerTool()
        imgp.setupImagePickerWith(MaxImagesCount: 5, superVC: self) { (asset, img) in
            //获取缩略图，耗时较短
            self.isSave = true
            self.uiimageData.removeAll()
            self.imgData.removeAll()
            CLImagePickerTool.convertAssetArrToOriginImage(assetArr: asset, scale: 2, successClouse: { (i, p) in
                self.imgData.append("123")
                self.uiimageData.append(i)
                self.tableView.reloadData()
            }, failedClouse: {
                
            })
        }
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "保存", style: .plain, target: self, action: #selector(self.save(_:)))
        
        jd = jsonFormater(data: data)
        
        
        
        if jd["key"].stringValue == "bank_attachments" {
            self.tableView.register(R.nib.addImageTableViewCell(), forCellReuseIdentifier: "addImageTableViewCell")
            self.tableView.isHidden = false
            self.btnImg.isHidden = true
            self.tableView.rowHeight = 234
            self.tableView.tableFooterView = UIView()
            if jd["value"].stringValue.isEmpty {
                self.imgData.append("")
            }else {
                
                
                jd["value"].stringValue.split(separator: ",").forEach { (s) in
                    let jwt = try? decode(jwt: String( s ))
                    let js1 = jsonFormater(data:jwt?.body as Any)
                    
                    imgData.append(js1["download"].stringValue)
                    
                    
                }
                
                
            }
            self.tableView.reloadData()
        }else {
            
            self.tableView.isHidden = true
            self.btnImg.isHidden = false
            
            if jd["value"].stringValue.isEmpty {
                
            }else {
                
                let jwt = try? decode(jwt: String(jd["value"].stringValue.split(separator: ",").first ?? ""))
                let js1 = jsonFormater(data:jwt?.body as Any)
                self.btnImg.kf.setBackgroundImage(with: ImageResource.init(downloadURL: URL.init(string:js1["download"].stringValue)!), for: .normal)
                self.btnImg.setImage(UIImage(), for: .normal)
            }
        }
        
        // Do any additional setup after loading the view.
    }
    
    @objc func save(_ bar : UIBarButtonItem) {
        //        self.data["value"] = self.tfInput.text!
        if self.isSave == false {
            showMessage(message: "请先选择图片")
            return;
        }
        
        
        
        upload()
//
    }


    
    func upload() -> Void {
        
        showHUD()
        
        if jd["key"].stringValue == "bank_attachments" {
            NetWorkRequest(.fileToken()) { (res) -> (Void) in
                if res["code"] as! String == "000000" {
                    let jd = jsonFormater(data: res["data"] as Any)
                    
                    NetWorkRequest(.uploadImage(url: jd["url"].stringValue, token: jd["token"].stringValue, data: UIImageJPEGRepresentation(self.uiimageData[0], 0.6) ?? UIImagePNGRepresentation(self.uiimageData[0])! ), completion: { (res) -> (Void) in
                        let d2 = jsonFormater(data: res)
                        if d2["jwt"].stringValue.isEmpty == false {
                            
                            self.uiimageData.remove(at: 0)
                            
                            self.urls.append(d2["jwt"].stringValue)
                            
                            if self.uiimageData.count <= 0 {
                            
                                self.bl?(["key":self.data["key"] as! String,"value":self.urls.joined(separator: ",")])
                                dismissHUD()
                                self.navigationController?.popViewController(animated: true)
                            }else {
                               self.upload()
                            }
                        }
                    })
                }
            }
        }else {
            NetWorkRequest(.fileToken()) { (res) -> (Void) in
                if res["code"] as! String == "000000" {
                    let jd = jsonFormater(data: res["data"] as Any)
                    showHUD()
                    NetWorkRequest(.uploadImage(url: jd["url"].stringValue, token: jd["token"].stringValue, data: UIImageJPEGRepresentation(self.btnImg.backgroundImage(for: .normal)!, 0.6) ?? UIImagePNGRepresentation(self.btnImg.backgroundImage(for: .normal)!)! ), completion: { (res) -> (Void) in
                        let d2 = jsonFormater(data: res)
                        if d2["jwt"].stringValue.isEmpty == false {
                            
                            self.bl?(["key":self.data["key"] as! String,"value":d2["jwt"].stringValue])
                            
                            self.navigationController?.popViewController(animated: true)
                        }
                    })
                }
            }
        }
    }
    
    @IBAction func selImg(_ sender: UIButton) {
        
        
        
        let imgp = CLImagePickerTool()
        
        if jd["key"].stringValue == "bank_attachments" {
            
            imgp.setupImagePickerWith(MaxImagesCount: 5, superVC: self) { (asset, img) in
                //获取缩略图，耗时较短
                self.isSave = true
                self.uiimageData.removeAll()
                self.imgData.removeAll()
                CLImagePickerTool.convertAssetArrToOriginImage(assetArr: asset, scale: 2, successClouse: { (i, p) in
                    self.imgData.append("123")
                    self.uiimageData.append(i)
                    self.tableView.reloadData()
                }, failedClouse: {
                    
                })
            }
        }else {
            
            imgp.setupImagePickerWith(MaxImagesCount: 1, superVC: self) { (asset, img) in
                //获取缩略图，耗时较短
                self.isSave = true
                CLImagePickerTool.convertAssetArrToOriginImage(assetArr: asset, scale: 2, successClouse: { (i, p) in
                    self.btnImg.setBackgroundImage(i, for: .normal)
                    self.btnImg.setImage(UIImage(), for: .normal)
                }, failedClouse: {
                    
                })
            }
        }
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
